<template name="dashboard">
    <div>
        <div id="container"></div>
        <div
            ref="marker"
            class="marker"
            v-show="markerVisible"
            :style="{ left: pixel.x + 26 + 'px', top: pixel.y - 16 + 'px' }"
        >
            <img
                :src="markerClose"
                alt=""
                class="marker_close"
                @click="compOverlayClose"
            />
            <div class="marker_header">
                <div>路口信息</div>
                <div>
                    <img :src="markerSxt" alt="" />
                    <img :src="markerSy" alt="" />
                </div>
            </div>
            <div class="marker_container">
                <div class="marker_container_item">
                    <div class="marker_container_item_title">所属位置</div>
                    <div class="marker_container_item_desc">
                        {{ markerRecord.name }}
                    </div>
                </div>
                <div class="marker_container_item">
                    <div class="marker_container_item_title">持续时间</div>
                    <div class="marker_container_item_desc">
                        {{ markerRecord.congestionDuration }}秒
                    </div>
                </div>
                <div class="marker_container_item">
                    <div class="marker_container_item_title">拥堵长度</div>
                    <div class="marker_container_item_desc">
                        {{ markerRecord.congestion }}米
                    </div>
                </div>
                <div class="marker_container_item">
                    <div class="marker_container_item_title">拥堵类型</div>
                    <div class="marker_container_item_desc">
                        {{
                            markerRecord.congestionType === 1 ? "常发" : "异常"
                        }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import "echarts";
import yellowIcon from "@/assets/dashboard/icon_yellow@2x.png";
import warnIcon from "@/assets/dashboard/icon_warn@2x.png";
import dangerIcon from "@/assets/dashboard/icon_danger@2x.png";
import lineGreen from "@/assets/dashboard/line_green.png";
import markerSxt from "@/assets/dashboard/marker_sxt@2x.png";
import markerSy from "@/assets/dashboard/marker_sy@2x.png";
import markerClose from "@/assets/dashboard/marker_close.png";

// import lineOrange from "@/assets/dashboard/link_orange.png";
// import linePink from "@/assets/dashboard/line_pink.png";
// import lineRed from "@/assets/dashboard/line_red.png";

import {
    junctionCongestionList,
    lineStringIndexList,
} from "@/services/dashborad";
import dayjs from "dayjs";
import { wgs84tobd09 } from "@/utils/map";
import { CONGESTION, SEVERE_CONGESTION, SLOW_DOWN } from "./constants";
const createMap = () => {
    const map = new BMapGL.Map("container");
    const point = new BMapGL.Point(116.404, 39.915);
    map.centerAndZoom(point, 15);
    map.enableScrollWheelZoom(true);
    map.setMapStyleV2({
        styleId: "4e4376721b62bd7c018312fde9e2efaa",
    });
    return map;
};

const map = ref<any>(null);
const createPolyLine = ({ points = [], mapInstance = {}, record }: any) => {
    let imgUrl = lineGreen;
    if (record.type) {
        imgUrl = lineGreen;
    }
    console.log(points);

    const polyline = new BMapGL.Polyline(
        [
            ...points.map((point: any[]) => {
                return new BMapGL.Point(...wgs84tobd09(...point));
            }),
        ],
        {
            strokeColor: "blue",
            strokeTexture: {
                url: imgUrl,
                width: 16,
                height: 64,
            },
            strokeWeight: 8,
            strokeOpacity: 0.8,
        }
    );

    mapInstance?.addOverlay?.(polyline);
    return polyline;
};

const createLable = ({
    point = [116.404, 39.915],
    offset = [0, 0],
    text,
    mapInstance,
}: any) => {
    const opts = {
        position: new BMapGL.Point(...wgs84tobd09(...point)), // 指定文本标注所在的地理位置
        offset: new BMapGL.Size(...offset), // 设置文本偏移量
    };
    // 创建文本标注对象
    var label = new BMapGL.Label(text, opts);
    // 自定义文本标注样式

    label.setStyle({
        color: "#C0D9F2",
        borderRadius: "4px",
        borderColor: "#5286CE",
        backgroundColor: "rgba(8,27,53,0.85)",
        padding: "6px",
        fontSize: "14px",
        height: "30px",
        lineHeight: "14px",
        fontFamily: "微软雅黑",
    });
    mapInstance?.addOverlay?.(label);
    return label;
};
const marker = ref<any>(null);
const markerVisible = ref<boolean>(false);
const pixel = ref<any>({ x: 0, y: 0 });
const compOverlay = ref<any>(null);
const markerRecord = ref<any>({});
const compOverlayClose = () => {
    markerVisible.value = false;
    map.value.removeOverlay(compOverlay.value);
};
const createDOM = ({ point, record }: any) => {
    // 创建自定义覆盖物
    function ComplexCustomOverlay() {}
    ComplexCustomOverlay.prototype = new BMapGL.Overlay();
    ComplexCustomOverlay.prototype.initialize = function () {
        markerRecord.value = record;
        this._div = marker.value;
        this._div.onmouseover = function () {};
        this._div.onmouseout = function () {};
        map.value.getPanes().labelPane.appendChild(this._div);
        return this._div;
    };
    ComplexCustomOverlay.prototype.draw = function () {
        pixel.value = map.value.pointToOverlayPixel(point);
    };
    markerVisible.value = true;
    const myCompOverlay: any = new (ComplexCustomOverlay as any)();
    map.value.addOverlay(myCompOverlay);
    compOverlay.value = myCompOverlay;
    return myCompOverlay;
};

const points = ref<any>([]);
const createIcon = ({
    point = [],
    type,
    size = [52, 62],
    mapInstance,
    record,
}: any) => {
    let iconImg = yellowIcon;
    //  1 畅通，2 缓行，3 拥堵，4严重拥堵
    if (type === SLOW_DOWN) {
        iconImg = yellowIcon;
    }
    if (type === CONGESTION) {
        iconImg = warnIcon;
    }
    if (type === SEVERE_CONGESTION) {
        iconImg = dangerIcon;
    }
    // 创建小车图标
    const icon = new BMapGL.Icon(iconImg, new BMapGL.Size(...size));
    // 创建Marker标注，使用小车图标
    const pt = new BMapGL.Point(...wgs84tobd09(...point));
    const marker = new BMapGL.Marker(pt, {
        icon,
    });
    marker.addEventListener("mouseover", function () {
        if (marker.label) {
            marker.label.show();
        } else {
            marker.label = createLable({
                point,
                text: record.name,
                offset: [10, -60],
                mapInstance: map.value,
            });
        }
    });
    marker.addEventListener("mouseout", function () {
        marker.label.hide();
    });
    marker.addEventListener("click", function () {
        createDOM({
            point: pt,
            record,
        });
    });
    points.value.push(marker);
    // 将标注添加到地图
    mapInstance?.addOverlay?.(marker);
    return marker;
};
const junctionCongestionListData = ref<any[]>([]);
const locations = ref<any[]>([]);
const getJunctionCongestionList = async () => {
    const { data } = await junctionCongestionList({
        currentTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    });
    junctionCongestionListData.value = data?.data || [];
    const location: any[] = data?.data?.[0]?.location || [];
    if (data?.data) {
        map.value?.centerAndZoom?.(
            new BMapGL.Point(...wgs84tobd09(...location)),
            15
        );
    }

    locations.value = junctionCongestionListData.value.map((item: any) => {
        createIcon({
            point: item.location,
            type: item.congestionLevel,
            mapInstance: map.value,
            record: item,
        });
        return wgs84tobd09(...item.location);
    });
};
const lineStringIndexListData = ref<any[]>([]);
const getLineStringIndexList = async () => {
    const { data } = await lineStringIndexList({
        currentTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    });
    return data?.data;
    // lineStringIndexListData.value = data?.data || [];
};
const initMap: any = () => {
    map.value = createMap();
};
onMounted(async () => {
    initMap();
    await getJunctionCongestionList();
    const lineStringIndexListData = await getLineStringIndexList();

    map.value.addEventListener("zoomend", function () {
        const zoom = map.value.getZoom(); // 获取缩放级别
        if (zoom > 15) {
            points.value.forEach((item: any) => {
                item.show();
            });
        } else {
            points.value.forEach((item: any) => {
                item.hide();
            });
        }
    });
    // addCluster();

    var icon1 =
        "//mapopen-pub-jsapigl.bj.bcebos.com/svgmodel/Icon_road_red_arrow.png";
    var icon2 =
        "//mapopen-pub-jsapigl.bj.bcebos.com/svgmodel/Icon_road_blue_arrow.png";
    var icon3 =
        "//mapopen-pub-jsapigl.bj.bcebos.com/svgmodel/Icon_road_green_arrow.png";
    var upTwo = "//mapopen-pub-jsapigl.bj.bcebos.com/svgmodel/up-two.png";
    var lineLayer: any = null;
    // 添加图层
    function addLineLayer() {
        // console.log(lineStringIndexListData.map((item) => item.lineString[0]));
        // const data = {
        //     type: "FeatureCollection",
        //     features: [
        //         {
        //             type: "Feature",
        //             properties: {
        //                 name: "demo1",
        //             },
        //             geometry: {
        //                 type: "LineString",
        //                 coordinates: lineStringIndexListData.map(
        //                     (item) => item.lineString[0]
        //                 ),
        //             },
        //         },
        //     ],
        // };
        if (!lineLayer) {
            lineLayer = new BMapGL.LineLayer({
                enablePicked: true,
                autoSelect: true,
                pickWidth: 30,
                pickHeight: 30,
                opacity: 1,
                selectedColor: "blue", // 选中项颜色
                style: {
                    sequence: true, // 是否采用间隔填充纹理，默认false
                    marginLength: 8, // 间隔距离，默认16，单位像素
                    borderColor: "rgba(0,125,125,1)",
                    borderMask: true, // 是否受内部填充区域掩膜，默认true,如果存在borderWeight小于0，则自动切换false
                    borderWeight: 2, // 描边宽度，可以设置负值
                    strokeWeight: 6, // 描边线宽度，默认0
                    strokeLineJoin: "miter", //描边线连接处类型, 可选'miter', 'round', 'bevel'
                    strokeLineCap: "square", // 描边线端头类型，可选'round', 'butt', 'square'，默认round
                    // 填充纹理图片地址，默认是空。图片需要是竖向表达，在填充时会自动横向处理。
                    strokeTextureUrl: [
                        "match",
                        ["get", "name"],
                        "demo1",
                        upTwo,
                        "demo2",
                        icon1,
                        "demo3",
                        icon2,
                        icon3,
                    ],
                    strokeTextureWidth: [
                        "match",
                        ["get", "name"],
                        "demo1",
                        32,
                        16,
                    ],
                    strokeTextureHeight: [
                        "match",
                        ["get", "name"],
                        "demo1",
                        64,
                        64,
                    ],
                    strokeColor: [
                        "case",
                        ["boolean", ["feature-state", "picked"], false],
                        "#6704ff",
                        [
                            "match",
                            ["get", "name"],
                            "demo1",
                            "#ce4848",
                            "demo2",
                            "red",
                            "demo3",
                            "#666",
                            "#6704ff",
                        ],
                    ],
                    strokeOpacity: 0.5,
                },
            });
        }

        map.value.addNormalLayer(lineLayer);
        // console.log(data);

        // lineLayer.setData(data);
    }

    addLineLayer();
});
</script>

<style lang="scss" scoped>
#container {
    width: 100vw;
    height: 100vh;
}
.marker {
    position: absolute;
    background: url(@/assets/dashboard/marker_bg@2x.png) no-repeat center center /
        100% 100%;
    padding: 12px 14px 18px;
    width: 328px;
    height: 214px;
    box-sizing: border-box;
    .marker_close {
        position: absolute;
        width: 28px;
        height: 28px;
        top: -14px;
        right: -14px;
    }
    .marker_header {
        display: flex;
        justify-content: space-between;
        font-weight: 600;
        font-size: 16px;
        color: #ffffff;
        line-height: 24px;
        img {
            &:first-of-type {
                width: 80px;
            }
            &:nth-of-type(2) {
                width: 60px;
            }
            margin-left: 10px;
        }
    }
    .marker_container {
        margin-top: 10px;
        border: 1px solid #346694;
        .marker_container_item {
            display: flex;
            border-bottom: 1px solid #346694;
            &:last-of-type {
                border: none;
            }
            .marker_container_item_title {
                text-align: center;
                background: #113067;
                width: 84px;
                height: 34px;
                line-height: 34px;
                color: #c0d9f2;
                border-right: 1px solid #346694;
            }
            .marker_container_item_desc {
                padding-left: 14px;
                font-weight: 400;
                font-size: 14px;
                line-height: 34px;
                color: #c0d9f2;
                background: #041b40;
                flex: 1;
            }
        }
    }
}
</style>
